import React, { useEffect, useState, useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux'

import { canvas, Rect, line } from '@/util/canvas/index.js'
import scss from './index.module.scss'
import { getBoundingClientRect } from '@/util/common.js'

const Middle = () => {
  const widthArr = useSelector((store) => store.aside.widthArr)
  const visible = useSelector((store) => store.aside.visible)
  const { el, ctx } = useSelector((store) => store.middle.myCanvas)

  const dispatch = useDispatch()

  const [size, setSize] = useState({ width: 0, height: 0 })
  const [finish, setFinish] = useState(false)

  const bgRef = useRef()

  useEffect(() => {
    if (ctx && el) {
      const { width, height, left, top } = getBoundingClientRect('canvas')
      const myRect = new Rect({ color: '#ffffff', x: left, y: top, width: 200, height: 300 })
      console.log(myRect)
      console.log(myRect.render(ctx))
      // myRect.render(ctx)
      // rect(ctx, { color: '#ffffff', x: left, y: top, width: 200, height: 300 })
      // line(myCanvas, { moveX: left, moveY: top, lineX: 200, lineY: 0 })
    }
  }, [ctx])

  useEffect(() => {
    setBgSize()
  }, [visible])

  useEffect(() => {
    const { width, height } = size
    const { el, ctx } = canvas('canvas')
    el.style.background = 'red'
    dispatch({ type: 'setMyCanvas', myCanvas: { el, ctx } })
  }, [size])

  useEffect(() => {
    if (finish) {
      const { left, top } = getBoundingClientRect('canvas')
      // rect(ctx, { color: '#ffffff', x: left, y: top, width: 200, height: 300 })
    }
  }, [finish])

  function setBgSize() {
    let _width = 0
    for (const w of widthArr) {
      _width += parseFloat(w.width)
    }
    const w = document.body.clientWidth
    const width = (visible ? w - _width : w) - 40
    const height = bgRef.current.clientHeight - 40

    setSize({ width, height })
  }

  return (
    <div className={scss.middle} ref={bgRef}>
      <div style={size}>
        <canvas id="canvas" width={size.width} height={size.height}></canvas>
      </div>
    </div>
  )
}

export default Middle
